﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Mvc;
using WalkingTec.Mvvm.Core.Extensions;
using System.Linq;
using System.Collections.Generic;
using nERP.Model.Bas;
using nERP.Model._Admin;
using nERP.Model.Fin;
using nERP.ViewModel.Fin.PaymentVMs;
using nERP.Model;

namespace nERP.Fin.Controllers
{
    [AuthorizeJwtWithCookie]
    [ActionDescription("_Model.Payment")]
    [ApiController]
    [Route("/api/Fin/Payment")]
    public partial class PaymentController : BaseApiController
    {
        [ActionDescription("Sys.Get")]
        [HttpGet("{id}")]
        public IActionResult Get(string id)
        {
            var vm = Wtm.CreateVM<PaymentVM>(id);
            return Ok(vm);
        }

        [ActionDescription("Sys.Create")]
        [HttpPost("[action]")]
        public async Task<IActionResult> Create(PaymentVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoAddAsync();
                if (ModelState.IsValid)
                {
                    await vm.StartWorkflowAsync();
                }

                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }

        }

        [ActionDescription("Sys.Edit")]
        [HttpPut("[action]")]
        public async Task<IActionResult> Edit(PaymentVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoEditAsync(false);
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }
        }

        [ActionDescription("Sys.Approve")]
        [Public]
        [HttpPost("[action]")]
        public async Task<ActionResult> Approve(PaymentVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoEditAsync(false);
                //结算账户：收款加，付款则减
                var sa = DC.Set<SettlementAccount>().Where(x => x.Code.Equals(vm.Entity.SettlementAccountId)).SingleOrDefault();
                sa.NowAmount -= vm.Entity.TotalPrice;
                DC.UpdateEntity(sa);
                DC.SaveChanges();
                if (ModelState.IsValid)
                {
                    await vm.ContinueWorkflowAsync(vm.ActionName, vm.Remark);
                }
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }
        }


        [HttpPost("BatchEdit")]
        [ActionDescription("Sys.BatchEdit")]
        public ActionResult BatchEdit(PaymentBatchVM vm)
        {
            if (!ModelState.IsValid || !vm.DoBatchEdit())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(vm.Ids.Count());
            }
        }

        [HttpPost("BatchDelete")]
        [ActionDescription("Sys.Delete")]
        public IActionResult BatchDelete(string[] ids)
        {
            var vm = Wtm.CreateVM<PaymentBatchVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = ids;
            }
            else
            {
                return Ok();
            }
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(ids.Count());
            }
        }

        [ActionDescription("Sys.DownloadTemplate")]
        [HttpGet("GetExcelTemplate")]
        public IActionResult GetExcelTemplate()
        {
            var vm = Wtm.CreateVM<PaymentImportVM>();
            var qs = new Dictionary<string, string>();
            foreach (var item in Request.Query.Keys)
            {
                qs.Add(item, Request.Query[item]);
            }
            vm.SetParms(qs);
            var data = vm.GenerateTemplate(out string fileName);
            return File(data, "application/vnd.ms-excel", fileName);
        }

        [ActionDescription("Sys.Import")]
        [HttpPost("Import")]
        public ActionResult Import(PaymentImportVM vm)
        {

            if (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData())
            {
                return BadRequest(vm.GetErrorJson());
            }
            else
            {
                return Ok(vm.EntityList.Count);
            }
        }




        [HttpGet("GetSuppliers")]
        [AllRights]
        public ActionResult GetSuppliers()
        {
            return Ok(DC.Set<Supplier>().GetSelectListItems(Wtm, x => x.SupplierName, x => x.SupplierCode.ToString()));
        }
        [HttpPost("[action]")]
        [AllRights]
        public ActionResult Select_GetSupplierBySupplierId(List<string> id)
        {
            var rv = DC.Set<Supplier>().CheckIDs(id).GetSelectListItems(Wtm, x => x.SupplierName, x => x.SupplierCode.ToString());
            return Ok(rv);
        }

        [HttpPost("[action]")]
        [AllRights]
        public ActionResult Select_GetPaymentBySupplier(List<string> id)
        {
            var rv = DC.Set<Payment>().CheckIDs(id, x => x.SupplierId).GetSelectListItems(Wtm, x => x.PayCode, x => x.PayCode);
            return Ok(rv);
        }


        [HttpGet("GetFrameworkUsers")]
        [AllRights]
        public ActionResult GetFrameworkUsers()
        {
            return Ok(DC.Set<FrameworkUser>().GetSelectListItems(Wtm, x => x.Name, x => x.ITCode.ToString()));
        }
        [HttpPost("[action]")]
        [AllRights]
        public ActionResult Select_GetFrameworkUserByFrameworkUserId(List<string> id)
        {
            var rv = DC.Set<FrameworkUser>().CheckIDs(id).GetSelectListItems(Wtm, x => x.Name, x => x.ITCode.ToString());
            return Ok(rv);
        }

        [HttpPost("[action]")]
        [AllRights]
        public ActionResult Select_GetPaymentByFrameworkUser(List<string> id)
        {
            var rv = DC.Set<Payment>().CheckIDs(id, x => x.MakeUserId).GetSelectListItems(Wtm, x => x.PayCode, x => x.PayCode);
            return Ok(rv);
        }


        [HttpGet("GetDicFields结算方式")]
        [AllRights]
        public ActionResult GetDicFields结算方式()
        {
            return Ok(DC.Set<DicField>().Where(x => x.DicDef.DicName == "结算方式").OrderBy(x => x.Order).GetSelectListItems(Wtm, x => x.DicFieldDes, SortByName: false));
        }
        [HttpPost("[action]")]
        [AllRights]
        public ActionResult Select_GetDicFieldByDicFieldId结算方式(List<string> id)
        {
            var rv = DC.Set<DicField>().Where(x => x.DicDef.DicName == "结算方式").CheckIDs(id).OrderBy(x => x.Order).GetSelectListItems(Wtm, x => x.DicFieldDes, SortByName: false);
            return Ok(rv);
        }

        [HttpPost("[action]")]
        [AllRights]
        public ActionResult Select_GetPaymentByDicField(List<string> id)
        {
            var rv = DC.Set<Payment>().CheckIDs(id, x => x.SettlementTypeId).GetSelectListItems(Wtm, x => x.PayCode, x => x.PayCode, SortByName: false);
            return Ok(rv);
        }


        [HttpGet("GetSettlementAccounts")]
        [AllRights]
        public ActionResult GetSettlementAccounts()
        {
            return Ok(DC.Set<SettlementAccount>().GetSelectListItems(Wtm, x => x.Name, x => x.Code.ToString()));
        }
        [HttpPost("[action]")]
        [AllRights]
        public ActionResult Select_GetSettlementAccountBySettlementAccountId(List<string> id)
        {
            var rv = DC.Set<SettlementAccount>().CheckIDs(id).GetSelectListItems(Wtm, x => x.Name, x => x.Code.ToString());
            return Ok(rv);
        }

        [HttpPost("[action]")]
        [AllRights]
        public ActionResult Select_GetPaymentBySettlementAccount(List<string> id)
        {
            var rv = DC.Set<Payment>().CheckIDs(id, x => x.SettlementAccountId).GetSelectListItems(Wtm, x => x.PayCode, x => x.PayCode);
            return Ok(rv);
        }


    }
}